<template>
  <page-card title="数据授权"
             :need-back="true">
    <slot name="form" />
    <a-row :gutter="16">
      <a-col :span="8">
        <a-card title="菜单权限"
                :bodyStyle="{height:'550px',overflow: 'auto'}">
          <div class="tree-box">
            <a-tree v-model="checkedKeys"
                    :tree-data="data"
                    :defaultExpandAll="true"
                    :expanded-keys="expandedKeysMemu"
                    @expand="handleExpand"
                    @select="clickTree" />
          </div>
        </a-card>
      </a-col>
      <a-col :span="16">
        <a-card title="功能权限"
                :bodyStyle="{height:'550px',overflow: 'hidden'}">
          <div class="radio-box">
            <a-radio-group name="radioGroup"
                           :value="radioValue"
                           @change="radioChange">
              <a-radio value="1">
                个人
              </a-radio>
              <a-radio value="2">
                本部门
              </a-radio>
              <a-radio value="3">
                本单位
              </a-radio>
              <a-radio value="4">
                自定义
              </a-radio>
            </a-radio-group>
            <a-checkbox :checked="checkSubValue"
                        @change="onSubChange">
              是否包含下级
            </a-checkbox>
          </div>
          <div v-if="radioValue == '4'"
               class="unit-tree-box">
            <a-row :gutter="16"
                   type="flex"
                   style="height:100%">
              <a-col :span="14"
                     style="height:100%;overflow-y:auto">
                <!-- :expandedKeys="expandedKeys" -->
                <a-tree v-if="update"
                        v-model="checkedKeysUnit"
                        checkable
                        :showIcon="true"
                        :autoExpandParent="autoExpandParent"
                        :expandedKeys="expandedKeys"
                        :selectedKeys="selectedKeys"
                        :load-data="loadTree"
                        :tree-data="treeDataUnit"
                        :checkStrictly="true"
                        @expand="onExpand"
                        @check="onCheck"
                        ref="unitTree">
                  <a-icon slot="switcherIcon"
                          type="caret-down" />
                  <a-icon slot="clazz"
                          type="appstore" />
                  <a-icon slot="unit"
                          type="home" />
                  <a-icon slot="dept"
                          type="bank" />
                  <template #title="item">
                    <span>{{ item.treeTitle }} </span>
                    <span v-if="!item.isLeaf"
                          style="margin-left:15px;z-index:111;">
                      <!-- v-if="!item.checked" -->
                      <span title="全选">
                        <a-icon type="plus-square"
                                @click="addClick(item)" />
                      </span>
                      <span title="取消全选"
                            style="margin-left:10px;">
                        <a-icon type="minus-circle"
                                @click="cancelClick(item)" />
                      </span>
                    </span>

                  </template>
                </a-tree>
              </a-col>
              <a-col :span="10">
                <div class="unit-tag-panel">
                  <div class="unit-tag-list clearfix">
                    <div class="unit-tag-item"
                         v-for="(tag,index) in selectData"
                         :key="index">
                      <a-tag>
                        {{ tag.title }}
                        <span class="tag-remove"
                              @click="onRemove(tag,index)">×</span>
                      </a-tag>
                    </div>
                  </div>
                </div>
              </a-col>
            </a-row>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <div style="text-align:center; padding:30px">
      <a-space size="small">
        <slot name="buttons" />
        <template>
          <a-button type="primary"
                    action
                    @click="handleSave">保存</a-button>
          <a-button type="primary"
                    actionss
                    @click="handleDelete">应用到所有根节点</a-button>
        </template>
      </a-space>
    </div>
  </page-card>
</template>
<script>

import Vue from 'vue'
import { Card } from 'ant-design-vue'
import arrayUtil from '@zh/common-utils/utils/array'
import { getOrderNo, getMenuListByRoleId, SysMenuroleSave, saveDataAuthTopMenu, getDataAuthUnitListByMenuId } from '../../api/role'
import { unitTreeLazyByRole } from '../../api/unit'
Vue.use(Card)
export default {
  data () {
    return {
      treeMap: {},
      data: [],
      expandedKeysMemu: [],
      checkedKeys: [],
      radioValue: '',
      menuId: '',
      MenuList: [],
      dataAuthText: '',
      dataList: [],
      checkSubValue: false,
      name: this.$route.query.name,
      appId: '',
      /// ////////////////////////////

      unitId: [], // 机构id
      // groupName: '', // 分组名称
      // groupType: '', // 分组类型
      orderNo: null, // 排序
      // 机构相关字段
      treeData: [], // 机构数组
      count: 0,
      autoExpandParent: false,
      expandedKeys: [],
      selectedKeys: [],
      // checkedKeys: [], // 选中的节点
      checkedKeysUnit: {
        // 选中的节点
        checked: [],
        halfChecked: []
      },
      // unitReplaceFields: { key: 'id', title: 'name' },
      treeDataUnit: [], // 机构树
      selectData: [], // 右边显示
      update: true
    }
  },
  created () {
    this.loadTree()
    this.loadActionList(() => {
      if (!this.$route.query.id) {
        getOrderNo().then((response) => {
          this.form.setFieldsValue(response)
        })
      }
    })
  },
  mounted () {
    this.appId = this.$route.query.id
  },
  methods: {
    onSubChange (value) {
      this.checkSubValue = value.target.checked
    },
    radioChange (value) {
      this.radioValue = value.target.value
    },
    reload () {
      // 移除组件
      this.update = false
      // 在组件移除后，重新渲染组件
      // this.$nextTick可实现在DOM 状态更新后，执行传入的方法。
      this.$nextTick(() => {
        this.update = true
      })
    },
    clickTree (value) {
      if (!value.length) {
        this.menuId = ''
        return
      }
      this.reload()
      this.expandedKeys = []
      this.loadTree()
      this.selectData = []
      this.menuId = value && value[0]
      this.MenuList.map((item) => {
        if (item.id == value[0]) {
          this.checkedKeysUnit.checked = item.dataAuthText
            ? JSON.parse(item.dataAuthText).unitIds
            : []
          this.radioValue = item.dataAuthType
          let containSub = item.dataAuthText
            ? JSON.parse(item.dataAuthText).containSub
            : ''
          this.checkSubValue = containSub == '1'
        }
      })
      getDataAuthUnitListByMenuId(this.appId, this.menuId).then((res) => {
        if (res) {
          res.map((item) => {
            this.selectData.push({
              value: item.id,
              title: item.fullName
            })
          })
        }
      })
    },
    /**
     * 加载权限树
     */
    loadActionList (callback) {
      getMenuListByRoleId(this.$route.query.id).then((response) => {
        response = response || []
        this.MenuList = response
        response.map((i) => {
          delete i.isLeaf
          i.title = i.name
          i.key = i.id
          if (!i.parentId || i.parentId == '' || i.parentId == '0') {
            i.parentId = null
          }
        })
        const { nodeList, nodeMap } = arrayUtil.toTree(
          response,
          'id',
          'parentId'
        )
        this.data = nodeList
        this.treeMap = nodeMap
        callback()
      })
    },
    /**
     * 树节点展开折叠
     */
    handleExpand (expandedKeys) {
      this.expandedKeysMemu = expandedKeys
    },
    handleSave () {
      let this_ = this
      // 保存方法
      let params = {
        menuId: this.menuId,
        roleId: this.appId,
        dataAuthType: this.radioValue,
        containSub: this.checkSubValue ? '1' : '0',
        unitIds: this.radioValue == '4' ? this.checkedKeysUnit.checked : []
      }
      if (!params.menuId) {
        this.message.info('请选择菜单')
        return
      }
      if (!params.dataAuthType) {
        this.message.info('请选择类型')
        return
      }
      if (params.dataAuthType == '4' && params.unitIds.length == 0) {
        this.message.info('请选择机构')
        return
      }
      SysMenuroleSave(params).then((res) => {
        if (res) {
          // this_.message.success('保存成功')
          this_.loadActionList(() => { })
        }
      })
    },
    handleDelete () {
      // 应用到所有方法
      let this_ = this
      let params = {
        menuId: this.menuId,
        roleId: this.appId,
        dataAuthType: this.radioValue,
        containSub: this.checkSubValue ? '1' : '0',
        unitIds: this.radioValue == '4' ? this.checkedKeysUnit.checked : []
      }
      if (!params.dataAuthType) {
        this.message.info('请选择类型')
        return
      }
      if (params.dataAuthType == '4' && params.unitIds.length == 0) {
        this.message.info('请选择机构')
        return
      }
      saveDataAuthTopMenu(params).then((res) => {
        if (res) {
          this.loadActionList(() => {
            if (!this.$route.query.id) {
              getOrderNo().then((response) => {
                this.form.setFieldsValue(response)
              })
            }
          })
          // this.$forceUpdate()
          // this_.message.success('应用成功')
        }
      })
    },
    /// ////////////////////////////////////////////////////////////////////////////
    // 删除tag
    onRemove (item, index) {
      let that = this
      let rs = that.checkedKeysUnit.checked.findIndex((c) => c == item.value)
      let keys = [...that.checkedKeysUnit.checked]
      keys.splice(rs, 1)
      this.selectData.splice(index, 1)
      that.checkedKeysUnit.checked = keys
      // that.$refs.tree.$forceUpdate()
    },
    onExpand (expandedKeys, info) {
      this.autoExpandParent = false
      this.expandedKeys = expandedKeys
    },
    // 点击复选框触发
    onCheck (checkedKeys, info) {
      this.checkedKeysUnit.checked = checkedKeys.checked
      if (info.checked) {
        let o = this.selectData.map((i) => {
          return i.value != info.node.dataRef.id
        })
        if (o) {
          this.selectData.push({
            value: info.node.dataRef.id,
            title: info.node.dataRef.treeTitle
          })
        }
      } else {
        let o = []
        this.selectData.map((i) => {
          if (i.value != info.node.dataRef.id) {
            o.push(i)
          }
        })
        this.selectData = o
      }
    },
    // 全选
    addClick (item) {
      Promise.all([this.loadTree(item)]).then((res) => {
        this.autoExpandParent = true
        this.getClick(item, 'add')
      })
    },
    // 取消全选
    cancelClick (item) {
      Promise.all([this.loadTree(item)]).then((res) => {
        this.getClick(item, 'del')
        this.selectedKeys = []
      })
    },
    getClick (data, type) {
      if (type === 'add') {
        if (this.checkedKeysUnit.checked.indexOf(data.key) == -1) {
          this.checkedKeysUnit.checked.push(data.key)
          let o = this.selectData.map((i) => {
            return i.value != data.key
          })
          if (o) {
            this.selectData.push({
              value: data.id,
              title: data.treeTitle
            })
          }
        }
        const addchildren = data.dataRef ? data.dataRef.children : data.dataRef
        if (addchildren && addchildren.length > 0) {
          for (let i = 0; i < addchildren.length; i++) {
            const addData = addchildren[i]
            this.getClick(addData, 'add')
          }
        }
      } else {
        let o = []
        this.selectData.map((i) => {
          if (i.value != data.key) {
            o.push(i)
          }
        })
        this.selectData = o
        if (this.checkedKeysUnit.checked.indexOf(data.key) >= 0) {
          this.checkedKeysUnit.checked = this.checkedKeysUnit.checked.filter(
            (k) => k !== data.key
          )
        }
        const delchildren = data.dataRef ? data.dataRef.children : data.dataRef
        if (delchildren && delchildren.length > 0) {
          for (let i = 0; i < delchildren.length; i++) {
            const delData = delchildren[i]
            this.getClick(delData, 'del')
          }
        }
      }
    },
    // 机构树懒加载
    loadTree (treeNode) {
      let that = this
      let id = !treeNode ? 0 : treeNode.dataRef.id
      return new Promise((resolve) => {
        unitTreeLazyByRole(id, that.$route.query.id).then(res => {
          if (treeNode) {
            treeNode.dataRef.children = res
            resolve()
          } else {
            that.treeDataUnit = res
          }
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.border {
  border: 1px solid #e8e8e8;
  border-bottom: 0;
  border-top: 0;
  border-left: 0;
  margin: 0 5px;
  min-height: 400px;
}
.radio-box {
  padding-bottom: 20px;
  display: flex;
  justify-content: space-between;
}
.tag-remove {
  display: inline-block;
  font-size: var(--font-size-16);
  cursor: pointer;
}
.subordinate {
  padding: 8px 10px;
  text-align: right;
}
.unit-tree-box {
  height: 450px;
  border: 1px solid #d9d9d9;
}
.unit-tag-panel {
  height: 449px;
  border-left: 1px solid #d9d9d9;
  padding: 15px;
}
.unit-tag-list {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  .unit-tag-item {
    margin-bottom: 5px;
  }
}
::v-deep .ant-checkbox-group-item {
  width: 100%;
  padding: 5px 0;
}
</style>
